package com.shanghaionstar.home;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.enumtype.CategoryType;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.ptr.PtrDefaultHandler;
import com.onstar.cn.weight.ptr.PtrFrameLayout;
import com.onstar.cn.weight.ptr.PtrHandler;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.iview.IPreferentialView;
import com.shanghaionstar.home.life.AssuranceFragment;
import com.shanghaionstar.home.life.OwnerLifeActivity;
import com.shanghaionstar.home.life.RenewalFragment;
import com.shanghaionstar.home.presenter.PreferentialPresenter;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.login.LoginActivity;
import com.shanghaionstar.login.register.JoinMeUtils;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.user.adapter.CommonAdapter;
import com.shanghaionstar.user.adapter.ViewHolder;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.ListViewUtil;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.vehicle_ownerlife.VehicleCheckMaintainHelper;
import com.shanghaionstar.vehicle_ownerlife.VehicleInspectionActivity;
import com.shanghaionstar.weight.OnStarPtrHeader;
import com.shanghaionstar.weight.TopLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by 7828wc on 16/6/29.
 * 车主生活界面
 */
@ContentView(R.layout.home_activity_preferential_main)
public class PreferentialActivity extends SwipeActivity implements IPreferentialView {
    @FindViewById
    private PtrFrameLayout refresh_layout;
    @FindViewById
    private RelativeLayout no_data_rl;
    @FindViewById(R.id.data_layout)
    private ListView mHotLv;
    @FindViewById
    private ProgressLayout progress_layout;
    @FindViewById
    private TextView no_perfer_dealer_tv;
    @FindViewById
    private TopLayout top_layout;

    interface IOwnerLifeToken {
        String OWNER_MAINTAIN = "maintain";
        String OWNER_INSURANCE = "insurance";
        String OWNER_RENEW = "renew";
        String OWNER_INSPECTION = "inspection";
    }

    public static final String NATIVE_SHOW_TYPE = "1";

    private Integer[] resIds = {R.drawable.owner_life_loading_fail_big, R.drawable.owner_life_loading_fail_big, R.drawable.owner_life_loading_fail_big};

    private GridView mOwnerGv;
    private TextView mOwnerTv;
    private GridView mHousekeeperGv;
    private PreferentialPresenter presenter;
    private DisplayImageOptions commonOption;
    private boolean isMaintainDisable = false;
    private boolean isCanRefresh = true;
    private VehicleCheckMaintainHelper helper;
    private Map<String, List<PreferentialResEntity>> allCategoryTypeData;

    private ILoginListener mListener;

    private Rect mRect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new PreferentialPresenter(getScheduler());
        helper = new VehicleCheckMaintainHelper(this);
        presenter.setView(this);
        setLoading(true);
        getData();
        commonOption = OnstarApplication.getOptions(true, false, R.drawable.hot_load_failed);
        commonOption = OnstarApplication.getOptions(true, false, R.drawable.owner_life_loading_fail_big);
        setUpRefreshLayout();
        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.MyPrivilege_Return.getStringValue());
                PreferentialActivity.this.finish();
            }
        });
        setupHeaderView();
        initListener();
    }

    private void getData() {
        BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.OwnerLife_All.getStringValue());
        String category = CategoryType.CAR_MANAGER.value() + "," + CategoryType.LIFE_MANAGER.value() + "," + CategoryType.HOT_PROMOTION.value();
        presenter.getMyDiscount(category);
    }


    private void setUpRefreshLayout() {
        OnStarPtrHeader header = new OnStarPtrHeader(this);
        refresh_layout.setHeaderView(header);
        refresh_layout.addPtrUIHandler(header);
        refresh_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        mHotLv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //到头部了
//没有到头部
                        isCanRefresh = mHotLv.getFirstVisiblePosition() == 0 && mHotLv.getChildAt(0).getTop() == 0;
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        isCanRefresh = true;
                        break;
                }

                return false;
            }
        });
        refresh_layout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                Rect rect = new Rect();
                mOwnerTv.getGlobalVisibleRect(rect);
                if (isCanRefresh && rect.top >= mRect.top) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
                } else {
                    return false;
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getData();
            }
        });
    }


    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        refresh_layout.refreshComplete();
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    public boolean refreshItems(Context context) {
        if (!ApplicationUtil.getInstance().isLogin()) {
            return true;
        } else {
            String loginRole = ApplicationUtil.getInstance().getLoginRole();
            boolean isNull = CommonUtil.isNull(loginRole);
            boolean isVisitor = !isNull & loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR);
            boolean isOwner = !isNull && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
            return isOwner || isVisitor;
        }
    }

    private void initListener() {
        mHousekeeperGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!ApplicationUtil.getInstance().isLogin()) {
                    Intent it = new Intent(PreferentialActivity.this, LoginActivity.class);
                    startActivity(it);
                    return;
                }
                String loginRole = ApplicationUtil.getInstance().getLoginRole();
                boolean isNull = CommonUtil.isNull(loginRole);
                boolean isVisitor = !isNull & loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR);
                if (ApplicationUtil.getInstance().isLogin() && isVisitor) {
                    showUpgradeDia();
                    return;
                }
//                ((OnstarFlowCommonAdapter) parent.getAdapter()).setClickPosition(position);
//                ((OnstarFlowCommonAdapter) parent.getAdapter()).notifyDataSetChanged();

                PreferentialResEntity entity = allCategoryTypeData.get(CategoryType.LIFE_MANAGER.value()).get(position);
                presenter.onCommonItemClick(entity, position);
            }
        });

        mHotLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    int pos = position - 1;
                    if (pos >= 0)
                        presenter.onItemClick(allCategoryTypeData.get(CategoryType.HOT_PROMOTION.value()).get(pos), pos);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });



        mOwnerGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!ApplicationUtil.getInstance().isLogin()) {
                    new LoginUtil().loginAndActionCallBack(PreferentialActivity.this, RxConstants.MORE_PAGE,mListener = new ILoginListener() {
                        @Override
                        public void onLogin(Bundle bundle, String resultCode) {
                            notifyOwnerLifeDataChange(allCategoryTypeData);
                        }
                    }, null);
                    return;
                }
                if (ApplicationUtil.getInstance().isLogin() && ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(Constants.VISITOR)) {
                    showUpgradeDia();
                    return;
                }
                if (ApplicationUtil.getInstance().isLogin() && ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(Constants.OWNER)) {
                    PreferentialResEntity entity = mCarManagerEntities.get(position);
                    if (entity != null) {
                        String callFunc = entity.getCallFuncNm();
                        if (getString(R.string.owner_life_rescue).equals(entity.getTitle())) {//道路救援请求地址需要加密
                            BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_RoadsideService.getStringValue());
                            jumpToWebView(getString(R.string.owner_life_rescue));
                        } else if (NATIVE_SHOW_TYPE.equalsIgnoreCase(entity.getShowType())) {
                            if (IOwnerLifeToken.OWNER_MAINTAIN.equalsIgnoreCase(callFunc)) {
                                BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_Maintainence.getStringValue());
                                if (!isMaintainDisable)
                                    helper.gotoCheckMaintain();
                            } else if (IOwnerLifeToken.OWNER_INSURANCE.equalsIgnoreCase(callFunc)) {
                                BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_Insurance.getStringValue());
                                jumpToOwnerLife(AssuranceFragment.class, mCarManagerEntities.get(position));
                            } else if (IOwnerLifeToken.OWNER_RENEW.equalsIgnoreCase(callFunc)) {
                                BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_DriveLicense.getStringValue());
                                jumpToOwnerLife(RenewalFragment.class, mCarManagerEntities.get(position));
                            } else if (IOwnerLifeToken.OWNER_INSPECTION.equalsIgnoreCase(callFunc)) {
                                BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_Inspection.getStringValue());
                                jumpToView(VehicleInspectionActivity.class, mCarManagerEntities.get(position));
                            }
                        } else {
                            sendVoilationReport(entity);
                            presenter.getH5(mCarManagerEntities.get(position));
//                        jumpToWebView();
                        }
                    } else {
                        presenter.getH5(mCarManagerEntities.get(position));
                    }
                } else {
                    PreferentialResEntity entity = mCarManagerEntities.get(position);
                    String callFunc = entity.getCallFuncNm();
                    if (callFunc != null && callFunc.equalsIgnoreCase(IOwnerLifeToken.OWNER_MAINTAIN)) {
                        BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_Maintainence.getStringValue());
                        if (!isMaintainDisable)
                            helper.gotoCheckMaintain();
                    } else {
//                        sendVoilationReport(entity);
                        jumpToWebView(entity.getTitle());
                    }
                }
            }
        });
    }

    private void sendVoilationReport(PreferentialResEntity entity) {
        String title = entity.getTitle();
        String[] defaultOwnerLifeServices = getResources().getStringArray(R.array.owner_life_services);
        if (title != null && title.equalsIgnoreCase(defaultOwnerLifeServices[5]))
            BusinessUtil.sendReportByClickType(PreferentialActivity.this, FunctionNameFindId.Carbulter_Violation.getStringValue());
    }


    List<PreferentialResEntity> mCarManagerEntities;

    String[] nativeTokens = {IOwnerLifeToken.OWNER_INSURANCE,
            IOwnerLifeToken.OWNER_RENEW, IOwnerLifeToken.OWNER_INSPECTION};

    @Override
    public void onReponseSuccess(Map<String, List<PreferentialResEntity>> object) {
        refresh_layout.refreshComplete();
        if (object == null || object.isEmpty())
            return;
        allCategoryTypeData = object;
        List<PreferentialResEntity> commonEntranceEntities = object.get(CategoryType.LIFE_MANAGER.value());
        List<PreferentialResEntity> hotPromotionEntities = object.get(CategoryType.HOT_PROMOTION.value());
        List<PreferentialResEntity> carManagerEntities = notifyOwnerLifeDataChange(object);
        ListViewUtil.setGridViewHeightBasedOnChildren(mOwnerGv, 3);
        if (carManagerEntities != null || !carManagerEntities.isEmpty()) {
//            mHousekeeperGv.setAdapter(new OnstarFlowCommonAdapter<PreferentialResEntity>(PreferentialActivity.this, commonEntranceEntities, R.layout.hourse_keeper_item) {
//                @Override
//                public void convert(ViewHolder holder, PreferentialResEntity entity, int pos) {
//                    holder.setText(R.id.item_tv, entity.getTitle());
//                    ImageView hotIv = holder.getView(R.id.item_iv);
//                    ImageLoader.getInstance().displayImage(entity.getImgUrl(), hotIv, commonOption);
////                    if (getClickPosition() == pos) {
////                        holder.setBackgroundRes(R.id.item_ll,R.drawable.owner_life_card_p);
////                    } else {
////                        holder.setBackgroundRes(R.id.item_ll,R.drawable.owner_life_card_n);
////                    }
//                }
//            });
            mHousekeeperGv.setAdapter(new CommonAdapter<PreferentialResEntity>(PreferentialActivity.this, commonEntranceEntities, R.layout.hourse_keeper_item) {

                @Override
                public void convert(ViewHolder holder, PreferentialResEntity entity) {
                    holder.setText(R.id.item_tv, entity.getTitle());
                    ImageView hotIv = holder.getView(R.id.item_iv);
                    ImageLoader.getInstance().displayImage(entity.getImgUrl(), hotIv, commonOption);
                }
            });
        } else {
            houseKeeperInit();
        }
        LogManager.getInstance().d("the house keeper grid view height is below=======>>");
        ListViewUtil.setGridViewHeightBasedOnChildren(mHousekeeperGv, 3);
        final DisplayImageOptions hotOption = OnstarApplication.getOptions(true, false, R.drawable.owner_life_loading_fail_big);
        if (hotPromotionEntities != null && !hotPromotionEntities.isEmpty()) {
            mHotLv.setAdapter(new CommonAdapter<PreferentialResEntity>(PreferentialActivity.this, hotPromotionEntities, R.layout.preferential_hot_item) {
                @Override
                public void convert(ViewHolder holder, PreferentialResEntity myDiscountResp) {
                    ImageView hotIv = holder.getView(R.id.hot_iv);
                    ImageLoader.getInstance().displayImage(myDiscountResp.getImgUrl(), hotIv, hotOption);
                }
            });
        } else {
            hotActionInit();
        }

    }

    @Nullable
    private List<PreferentialResEntity> notifyOwnerLifeDataChange(Map<String, List<PreferentialResEntity>> object) {
        List<PreferentialResEntity> carManagerEntities = object.get(CategoryType.CAR_MANAGER.value());
        mCarManagerEntities = carManagerEntities;
        if (carManagerEntities != null && !carManagerEntities.isEmpty()) {
            mOwnerTv.setVisibility(View.VISIBLE);
            refreshOwnerDataByRole();
            setOwnerAdapter();
        } else {
            mOwnerTv.setVisibility(View.GONE);
        }
        return carManagerEntities;
    }

    private void refreshOwnerDataByRole() {
        boolean isNotProxy = refreshItems(PreferentialActivity.this);
        if (!isNotProxy) {
            String[] defaultOwnerLifeServices = getResources().getStringArray(R.array.owner_life_services);
            Iterator<PreferentialResEntity> it = mCarManagerEntities.iterator();
            while (it.hasNext()) {
                PreferentialResEntity entity = it.next();
                String callFun = entity.getCallFuncNm();
                for (String token : nativeTokens) {
                    if (callFun != null && callFun.contains(token))
                        it.remove();
                }
                String title = entity.getTitle();
                if (title != null && title.equalsIgnoreCase(defaultOwnerLifeServices[5]))
                    it.remove();
            }
        }
    }

    private void setOwnerAdapter() {
        mOwnerGv.setAdapter(new CommonAdapter<PreferentialResEntity>(PreferentialActivity.this, mCarManagerEntities, R.layout.owner_life_item) {
            @Override
            public void convert(ViewHolder holder, PreferentialResEntity entity) {
                holder.setText(R.id.item_tv, entity.getTitle());
                if (entity.getTitle().equalsIgnoreCase(getResources().getStringArray(R.array.owner_life_services)[0])) {
                    if (isMaintainDisable = !helper.isEnable()) {
                        holder.setImageResource(R.id.item_iv, R.drawable.owner_maintain_disable);
                    } else {
                        ImageView hotIv = holder.getView(R.id.item_iv);
                        ImageLoader.getInstance().displayImage(entity.getImgUrl(), hotIv, commonOption);
                    }
                } else {
                    ImageView hotIv = holder.getView(R.id.item_iv);
                    ImageLoader.getInstance().displayImage(entity.getImgUrl(), hotIv, commonOption);
                }
            }
        });
    }

    /**
     * 升级为车主
     */
    private void showUpgradeDia() {
        AlertDialogUtil.showAlertDialog(PreferentialActivity.this, R.string.dialog_warning, R.string.SB021_MSG013,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        JoinMeUtils.checkVisitor(PreferentialActivity.this);
                    }
                }, true, R.string.upgrade_to_owner);
    }


    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mListener != null)
            mListener = null;
        presenter.finish();
        presenter = null;
    }

    @Override
    public void onNoData(String type, boolean isSuccess) {
        refresh_layout.refreshComplete();
        houseKeeperInit();
        hotActionInit();
    }

    private void hotActionInit() {
//        final DisplayImageOptions hotOption = OnstarApplication.getOptions(true, false, R.drawable.pre_hot_failed);
        final DisplayImageOptions hotOption = OnstarApplication.getOptions(true, false, R.drawable.owner_life_loading_fail_big);
        List<PreferentialResEntity> testList = new ArrayList<>();
        testList.add(new PreferentialResEntity());
        mHotLv.setAdapter(new CommonAdapter<PreferentialResEntity>(PreferentialActivity.this, testList, R.layout.preferential_no_data_item) {
            @Override
            public void convert(ViewHolder holder, PreferentialResEntity myDiscountResp) {
//                ImageView hotIv = holder.getView(R.id.hot_iv);
//                ImageLoader.getInstance().displayImage(myDiscountResp.getImgUrl(), hotIv, hotOption);
            }
        });
    }

    private void houseKeeperInit() {
        mHousekeeperGv.setAdapter(new CommonAdapter<Integer>(PreferentialActivity.this, Arrays.asList(resIds), R.layout.preferential_common_item) {
            @Override
            public void convert(ViewHolder holder, Integer integer) {
                holder.setImageResource(R.id.item_iv, integer);
            }
        });
        ListViewUtil.setGridViewHeightBasedOnChildren(mHousekeeperGv, 3);
        mHousekeeperGv.setOnItemClickListener(null);
    }


    private void setupHeaderView() {
        LayoutInflater inflater = LayoutInflater.from(PreferentialActivity.this);
        final View headerView = inflater.inflate(R.layout.owner_life_header, null);
        mOwnerGv = (GridView) headerView.findViewById(R.id.owner_gv);
        mOwnerTv = (TextView) headerView.findViewById(R.id.owner_tv);
        mRect = new Rect();
        mOwnerTv.getGlobalVisibleRect(mRect);
        mHousekeeperGv = (GridView) headerView.findViewById(R.id.housekeeper_gv);
        mHotLv.addHeaderView(headerView);
    }


    private void jumpToWebView(String  title) {
//        Intent it = new Intent(PreferentialActivity.this, CommonWebViewActivity.class);
//        Bundle bundle = new Bundle();
//        String linkUrl = EncryptUtil.decryptBase64(PreferentialActivity.this, Constants.PREFIX_H5_URL) + Constants.ROAD_RESCUE;
//        bundle.putString("linkUrl", linkUrl);
//        it.putExtras(bundle);
//        startActivity(it);
        String linkUrl = Constants.CURRENT_PREFIX_H5_URL+ Constants.ROAD_RESCUE;
        WebDataEntity entity = new WebDataEntity();
        entity.setLinkUrl(linkUrl);
        entity.setTopTitle(title);
        entity.setWhat(IWebType.TYPE_NORMAL);
        CommonWebViewActivity.launchCommonWeb(PreferentialActivity.this,entity);
    }


    private void jumpToView(Class<?> clz, PreferentialResEntity entity) {
        Intent it = new Intent(PreferentialActivity.this, clz);
        it.putExtra("entity", entity);
        startActivity(it);
    }

    private void jumpToOwnerLife(Class<?> clz, PreferentialResEntity entity) {
        Intent it = new Intent(PreferentialActivity.this, OwnerLifeActivity.class);
        it.putExtra(FinalConstants.JUMP_FLAG, clz.getName());
        it.putExtra("entity", entity);
        startActivity(it);
    }


}
